package cn.wolfcode.service.impl;

import cn.wolfcode.dao.OrderDao;
import cn.wolfcode.domain.Order;
import cn.wolfcode.domain.Product;
import cn.wolfcode.feign.ProductFeign;
import cn.wolfcode.service.IOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RestTemplate restTemplate;
//    @Autowired  // 使用 nacos 实现服务的请求均衡分发 ==> 用了springcloudAlibaba负载均衡组件Ribbon后就可以不用了
//                                           ==> 实现原理即 在启动类注入RestTemplate 时, 贴上@LoadBalanced注解
//    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductFeign productFeign;

    @Override
    public Order createOrder(Long pid, Long uid) {
        log.info("product-service服务被调用了");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", pid);
        // 通过获取存放在nacos中的product-service服务集合,随机数指定索引,获取服务实例
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        int index = new Random().nextInt(instances.size());
//        ServiceInstance instance = instances.get(index);


        Order order = new Order();
        Product product = null;
        // 拼接参数 只使用 nacos服务治理 实现负载均衡调用
//        product = restTemplate.getForObject("http://"+ instance.getHost() +":"
//                + instance.getPort()  + "/product?pid=" + pid, Product.class);
        // 负载均衡 Ribbon的实现方式
//        product = restTemplate.getForObject("http://product-service/product?pid=" + pid, Product.class);
//        log.info("查询到{}号商品的信息,内容是:{}", pid, JSON.toJSONString(product));

        //======= 使用远程调用Feign实现（内部默认集成了负载均衡Ribbon）====
        product = productFeign.findByPid(pid);

        // 创建订单
        order.setPid(pid);
//        order.setPname(product.getPname() + ":" + instance.getPort());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());

        order.setUid(uid);
        order.setUsername("ming");
        order.setNumber(1);
        orderDao.save(order);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;
    }
}
